<template>
  <view class="course-list-page" :style="'padding-top:'+top+'px'">
    <view style="position: fixed;left: 0;background-color: #fbf9f5;z-index: 99;width: 100%;top: 0;padding-left: 15px;padding-right: 15px" :style="'padding-top:'+top+'px'">
      <view class="message-header">
        <image style="width: 1.8vh;height: 2.4vh;margin-right: 1vh;margin-top: 1rpx"
               :src="IMAGE_CONFIG.locationIndex">
        </image>
        <view style="width: 150rpx;" @click="jumpArea">{{ shortName }}</view>
      </view>
      <view class='productSort'>
        <view class='header acea-row row-center-wrapper block' style="border-bottom: none">
          <view class='acea-row row-between-wrapper input'>
            <text class='iconfont icon-sousuo'></text>

            <input type='text' placeholder='搜索感兴趣的课程' v-model="value" @confirm="searchSubmitValue"
                   confirm-type='search'
                   name="search" style="width: 74%;position: relative;left:-62rpx;"
                   placeholder-class='placeholder' maxlength="20"/>
            <view class="block" style="background-color: #8B5D3B;height: 60rpx;width: 20%;position: absolute;right:0;border-radius: 0 50rpx 50rpx 0;
          line-height: 60rpx;text-align: center;color: #FCFAF6" @click="searchSubmitValue(value)">搜索
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 筛选按钮部分一级 -->
    <view class="filter-container" style="margin-top: 200rpx">
      <view class="filter-row">
        <scroll-view class="scroll-x" scroll-x>
          <view class="filter-buttons" v-for="(row, rowIndex) in ageTags" :key="rowIndex">
            <view class="filter-button" style="font-size: 25rpx"
                  :class="{ active: ageIndex===rowIndex }"
                  @click="selectAge(row, rowIndex)" v-if="row.isShow">
              <image :src="row.icon" mode="aspectFill" style="width: 28rpx;height: 28rpx;margin-right: 12rpx"
                     v-if="row.icon"></image>
              {{ row.name }}
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <!-- 筛选按钮部分二级 -->
    <view class="filter-container">
      <view class="filter-row">
        <scroll-view class="scroll-x" scroll-x>
          <view class="filter-buttons" v-for="(row, index) in categoryTags" :key="index">
            <!--            v-for="(button, indexs) in row.childList"-->

            <view class="filter-button" style="padding: 5rpx 18rpx;margin-right: 12rpx"
                  :class="{ active: categoryIndex===index }"
                  @click="selectCategory(row.id,index)" v-if="row.isShow">
              {{ row.name }}
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <!-- 筛选按钮部分三级  价格 -->
    <view class="filter-container">
      <view class="filter-row">
        <scroll-view class="scroll-x" scroll-x>
          <view class="filter-buttons" v-for="(row, rowIndex) in buttonRows" :key="rowIndex">
            <view class="filter-button" style="padding: 4rpx 15rpx;margin-right: 12rpx"
                  :class="{ active: buttons===rowIndex }"
                  @click="selectButton(row, rowIndex)">
              {{ row.label }}
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="requestStatus === 'loading' && courses.length === 0" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">正在加载课程...</text>
    </view>

    <!-- 错误状态 -->
    <view v-if="requestStatus === 'error' && courses.length === 0" class="error-container" @click="retryLoad">
      <text class="error-text">{{ errorMessage || '加载失败' }}</text>
      <text class="retry-text">点击重试</text>
    </view>

    <!-- 课程列表部分 -->
    <view v-if="courses.length > 0" class="course-list">
      <view class="course-card" v-for="(course, index) in courses" :key="index" @click="jumpDetails(course.id)">
        <view class="card-header">
          <view style="position: absolute;top: 16rpx;left: 16rpx;background-color: rgba(255,255,255,.6);border-radius: 20px;width: 72rpx;height: 44rpx;
          display: flex;justify-content: center;align-items: center;">
            <image style="width: 28rpx;height: 28rpx;" :src="course.icon"></image>
          </view>
          <image :src="course.image" mode="aspectFill"></image>
          <view class="course-type-tag" :class="course.type === 0 ? 'offline' : 'online'">
            <image class="type-icon" :src="course.type === 0 ? IMAGE_CONFIG.xianXia : IMAGE_CONFIG.xianShang"></image>
            <text class="type-text">{{ course.type === 0 ? '线下课' : '线上课' }}</text>
          </view>
        </view>
        <view class="card-body">
          <view class="course-title">{{ course.name }}</view>

          <view class="course-info">
            <view class="course-age">{{ course.ageRange }}</view>
            <image
                style="position: absolute; top: -12px; right: 16px; width: 21px; height: 25px;"
                :src="IMAGE_CONFIG.logo2"
            ></image>
          </view>
          <view class="course-price">
            <text class="price-value">￥{{ course.price }}</text>
            <view class="course-study-num">{{ Math.floor(course.sales) + Math.floor(course.ficti) || 0 }}人学过</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多状态 -->
    <view v-if="courses.length > 0" class="load-more-container">
      <view v-if="loading" class="loading-more">
        <view class="loading-spinner-small"></view>
        <text class="loading-more-text">加载中...</text>
      </view>
      <view v-else-if="loadend" class="load-end">
        <text class="load-end-text">{{ loadTitle }}</text>
      </view>
      <view v-else class="load-more-btn" @click="getList">
        <text class="load-more-text">{{ loadTitle }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import animationType from '@/utils/animationType.js'
import {getCategoryList, productList} from "../../api/product";
import {getMerProListApi} from "../../api/merchant";
import {IMAGE_CONFIG} from '@/utils/imageConfig'
import {getCommonReverseGeocoder} from "../../api/new";
import { Debounce } from '@/utils/validate.js'

export default {
  data() {
    return {
      IMAGE_CONFIG: IMAGE_CONFIG.study,
      ageTags: [{name: '全部', isShow: true}],
      categoryTags: [],
      ageIndex: 0,
      buttons: 0,
      categoryIndex: 0,
      categorysIndex: 0,
      value: undefined,
      top: 0,
      winHeight: 0,
      showSkeleton: true, //骨架屏显示隐藏
      // 筛选按钮数据（三行）
      buttonRows:
          [
            {label: '0-1000元'},
            {label: '1000-3000元'},
            {label: '3000元以上'}
          ],
      where: {
        keyword: '',
        priceOrder: '',
        salesOrder: '',
        //news: 0,
        page: 1,
        limit: 10,
        cid: '', //商城使用
        merId: '',
        cids: '', //商户使用
      },
      keyword: '',
      shortName: '',
      lng: '',
      lat: '',
      // 课程数据
      courses: [],
      // 新增状态管理
      loading: false,
      loadend: false,
      loadTitle: '加载更多',
      isShow: false,
      // 防抖定时器
      searchTimer: null,
      // 请求状态
      requestStatus: 'idle', // idle, loading, success, error
      errorMessage: ''
    };
  },
  onLoad(options) {
    this.top = uni.getMenuButtonBoundingClientRect().top;
    let that = this
    uni.getSystemInfo({
      success: function (res) {
        that.winHeight = res.windowHeight
      },
    });
    this.$set(this, 'keyword', options.searchValue || '');
  },
  onShow() {
    const params = uni.getStorageSync('studyParams');
    if (params && params.shortName && params.lng && params.lat) {
      // 用本地存储的参数
      this.shortName = params.shortName;
      this.lng = params.lng;
      this.lat = params.lat;
      this.getTitList()
    } else {
      // 获取当前经纬度
      uni.getLocation({
        type: 'wgs84',
        success: (res) => {
          this.lng = res.longitude;
          this.lat = res.latitude;
          // 你可以在这里调用逆地理编码API获取shortName
          getCommonReverseGeocoder({lon:this.lng,lat:this.lat}).then(res=> {
            this.shortName = res.data.msg;
          })
          this.getTitList()
        },
        fail: () => {
          uni.showToast({ title: '定位失败', icon: 'none' });
        }
      });
    }
  },
  methods: {
    // 优化后的获取列表方法
    async getList() {
      // 如果正在加载，直接返回
      if (this.loading) {
        return;
      }

      try {
        this.loading = true;
        this.requestStatus = 'loading';
        this.errorMessage = '';

        // 构建请求参数
        const requestParams = this.buildRequestParams();
        console.log('请求参数:', requestParams);

        // 根据merId选择不同的API
        const apiCall = this.merId === 0 ? productList : getMerProListApi;
        const response = await apiCall(requestParams);

        // 处理响应数据
        this.handleResponseData(response.data);

      } catch (error) {
        console.error('获取课程列表失败:', error);
        this.handleRequestError(error);
      } finally {
        this.loading = false;
      }
    },

    // 构建请求参数
    buildRequestParams() {
      const params = { ...this.where };
      
      // 确保merId设置正确
      this.merId = 0;
      if (this.merId > 0) {
        params.merId = this.merId;
      }
      
      // 处理关键词编码
      params.keyword = encodeURIComponent(this.keyword || '');
      
      // 处理分类ID
      if (this.cid === 0) {
        params.cid = '';
        params.cids = '';
      } else {
        if (this.merId > 0) {
          params.cids = this.cid;
          params.cid = '';
        } else {
          params.cid = this.cid;
          params.cids = '';
        }
      }

      // 添加位置信息
      if (this.merId === 0) {
        params.lon = this.lng;
        params.lat = this.lat;
      }

      return params;
    },

    // 处理响应数据
    handleResponseData(data) {
      const list = data.list || [];
      const loadend = list.length < this.where.limit;
      
      // 更新状态
      this.loadend = loadend;
      this.loadTitle = loadend ? '已全部加载' : '加载更多';
      this.requestStatus = 'success';
      this.isShow = true;

      // 更新课程列表
      if (this.where.page === 1) {
        // 第一页，直接替换
        this.courses = list;
      } else {
        // 加载更多，追加数据
        this.courses = [...this.courses, ...list];
      }

      // 更新页码
      this.$set(this.where, 'page', this.where.page + 1);
      
      console.log('课程列表更新:', this.courses);
    },

    // 处理请求错误
    handleRequestError(error) {
      this.requestStatus = 'error';
      this.loadTitle = '加载失败，点击重试';
      
      const errorMsg = error.message || '网络请求失败';
      this.errorMessage = errorMsg;
      
      // 显示错误提示
      uni.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 2000
      });
    },

    // 防抖处理的选择分类方法
    selectCategory: Debounce(function(cid, index, indexs) {
      this.categoryIndex = index;
      this.cid = cid;
      this.resetPagination();
      this.updatePriceFilter();
      this.getList();
    }, 200),

    // 防抖处理的选择年龄方法
    selectAge: Debounce(function(age, index) {
      this.ageIndex = index;
      this.categoryTags = age.childList;
      
      // 自动选择第一个子分类
      if (this.categoryTags && this.categoryTags.length > 0) {
        const firstCategory = this.categoryTags[0];
        if (firstCategory.childList && firstCategory.childList.length > 0) {
          this.selectCategory(firstCategory.childList[0].id, 0, 0);
        } else {
          this.selectCategory(firstCategory.id, 0, 0);
        }
      }
      
      console.log('选择年龄分类:', age);
    }, 300),

    // 防抖处理的选择价格按钮方法
    selectButton: Debounce(function(button, rowIndex) {
      this.buttons = rowIndex;
      this.updatePriceFilter();
      this.resetPagination();
      this.getList();
    }, 300),

    // 重置分页
    resetPagination() {
      this.where.page = 1;
      this.loadend = false;
      this.loadTitle = '加载更多';
    },

    // 更新价格筛选
    updatePriceFilter() {
      switch (this.buttons) {
        case 0:
          this.$set(this.where, 'minPrice', 0);
          this.$set(this.where, 'maxPrice', 1000);
          break;
        case 1:
          this.$set(this.where, 'minPrice', 1000);
          this.$set(this.where, 'maxPrice', 3000);
          break;
        case 2:
          this.$set(this.where, 'minPrice', 3000);
          this.$delete(this.where, 'maxPrice');
          break;
        default:
          this.$delete(this.where, 'minPrice');
          this.$delete(this.where, 'maxPrice');
      }
    },

    // 优化后的获取分类列表方法
    async getTitList() {
      try {
        const response = await getCategoryList();
        this.$set(this, 'ageTags', response.data);
        this.categoryTags = this.ageTags[0].childList;
        this.cid = -2;
        
        // 初始化价格筛选
        this.updatePriceFilter();
        
        // 获取课程列表
        await this.getList();
        
      } catch (error) {
        console.error('获取分类列表失败:', error);
        uni.showToast({
          title: '获取分类失败',
          icon: 'none'
        });
      }
    },

    // 重试加载
    retryLoad() {
      if (this.requestStatus === 'error') {
        this.getList();
      }
    },

    jumpDetails(id) {
      uni.navigateTo({
        url: '/pages/discover/courseDetails/index?id=' + id
      })
    },
    jumpArea() {
      uni.navigateTo({
        url: `/pages/address/areaSelector/index`
      })
    },
    searchSubmitValue: function (e) {
      console.log(111)

      // if (this.$util.trim(e.detail.value).length > 0)
      if (this.$util.trim(this.value).length > 0)
        uni.navigateTo({
          animationType: animationType.type,
          animationDuration: animationType.duration,
          url: `/pages/goods/goods_list/index?searchValue=${this.value}&lat=${this.lat}&lng=${this.lng}`
        })
      else
        return this.$util.Tips({
          title: '请填写要搜索的产品信息'
        });
    }
  },
  onReachBottom() {
    // 只有在有数据且未加载完成时才触发加载更多
    if (this.courses.length > 0 && !this.loadend && !this.loading) {
      this.getList();
    }
  },
  
  // 组件销毁时清理定时器
  beforeDestroy() {
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
  }
}
</script>

<style lang="scss" scoped>
// 变量定义
$primary-color: #b86938; // 主色调（棕色）
$active-color: #8B4513; // 激活状态颜色
$text-gray: #999; // 次要文本颜色
$red: #f44336; // 价格颜色
$bg-light: #f9f9f9; // 卡片背景色
$border-radius: 8px; // 圆角大小
$padding-sm: 8rpx; // 小间距
$padding-md: 16rpx; // 中等间距
$padding-lg: 24rpx; // 大间距

// 页面整体样式
.course-list-page {
  padding: 0 15px;
  background-color: #FCFAF6;


  .message-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    position: relative;

    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #8B4513;
      width: 100rpx;
      text-align: center;
      margin: auto;
      font-weight: bold;
    }
  }

  // 筛选区域样式
  .filter-container {
    margin-bottom: $padding-lg;

    .filter-row {
      margin-bottom: 30rpx;
      //display: inline-block;
      .scroll-x {
        white-space: nowrap;

        .filter-buttons {
          display: inline-flex;

          .filter-button {
            display: flex;
            align-items: center;
            padding: 12rpx 32rpx;
            //background-color: $primary-color;
            color: #000;
            border-radius: $border-radius*3;
            text-align: center;
            font-size: 28rpx;
            white-space: nowrap;

            &.active {
              background-color: $active-color;
              color: white;
            }
          }
        }
      }
    }
  }

  // 课程列表样式
  .course-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .course-card {
      margin-top: 10px;;
      width: calc(50% - (15px / 2));
      margin-bottom: 15px;
      background-color: #F6F2EA;
      border-radius: $border-radius;
      overflow: hidden;

      .card-header {
        position: relative;
        height: 200rpx;
        overflow: hidden;
        /* 课程类型标签样式 */
        .course-type-tag {
          position: absolute;
          top: 0;
          left: 65%;
          display: flex;
          align-items: center;
          padding: 8rpx 16rpx;
          //border-radius: 20rpx;
          color: #fff;
          font-size: 22rpx;
          font-weight: 500;
          z-index: 10;
          width: 200rpx;

          &.offline {
            background: linear-gradient(135deg, #b3793b, #b3793b);
          }

          &.online {
            background: linear-gradient(135deg, #8e4c38, #8e4c38);
          }

          .type-icon {
            margin-right: 10rpx;
            width: 20rpx;
            height: 20rpx;
          }

          .type-text {
            font-size: 22rpx;
            font-weight: 500;
          }
        }
        image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .card-body {
        padding: $padding-md;

        .course-title {
          font-size: 25rpx;
          color: #6e5151;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          overflow: hidden;
        }

        .course-info {
          position: relative;
          height: 22px;

          .course-age {
            font-size: 24rpx;
            color: #6B7280;
            position: absolute;
            left: 0
          }
        }

        .course-price {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .price-value {
            font-size: 32rpx;
            color: #FF4D4F;
            font-weight: bold;
          }

          .course-study-num {
            font-size: 24rpx;
            padding: 4rpx 10rpx;
            color: #A28C72;
            background-color: #ffffff;
            border-radius: $border-radius*2;
          }
        }
      }
    }
  }

  .productSort {
    display: flex;
    flex-direction: column;
    width: 100%;
    position: relative;

    .con-box {
      flex: 1;
      display: flex;
      overflow: hidden;
    }
  }

  .productSort .header {
    width: 100%;
    padding-bottom: 6rpx;
    border-bottom: 1rpx solid #f5f5f5;
    position: relative;
    /*left: 28%;*/
  }

  .productSort .header .input {
    width: 100%;
    height: 60rpx;
    background-color: #F3F4F6;
    border-radius: 50rpx;
    box-sizing: border-box;
    padding: 0 25rpx;
  }

  .productSort .header .input .iconfont {
    font-size: 28rpx;
    color: #555;
  }

  .productSort .header .input .placeholder {
    color: #999;
  }

  .productSort .header .input input {
    font-size: 28rpx;
    height: 100%;
    width: 597rpx;
  }

  .productSort .header .input .input-box {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    height: 100%;
    width: 597rpx;
    color: #999999;
  }

  .productSort .aside {
    background-color: #fff;
    overflow-y: auto;
    overflow-x: hidden;
    width: 200rpx;
    height: 100%;
    overflow: hidden;
  }

  .productSort .aside .item {
    height: 100rpx;
    width: 100%;
    font-size: 26rpx;
    color: #424242;
  }

  .productSort .aside .item_text {
    padding-left: 20rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .productSort .aside .item.on {
    background-color: #f7f7f7;
    border-left: 4rpx solid var(--view-theme);
    width: 100%;
    text-align: center;
    @include main_color(theme);
    font-weight: bold;
  }

  .productSort .conter {
    flex: 1;
    height: 100%;
    padding: 0 14rpx;
    background-color: #f7f7f7;
  }

  .productSort .conter .listw .title {
    height: 100rpx;
    align-items: center;
  }

  .productSort .conter .listw .title .line {
    width: 100rpx;
    height: 2rpx;
    background-color: #f0f0f0;
  }

  .productSort .conter .listw .title .name {
    font-size: 28rpx;
    color: #333;
    margin: 0 30rpx;
    font-weight: bold;
  }

  .productSort .conter .listw .title .list_title,
  .productSort .conter .listw .title uni-image,
  .productSort .conter .listw .title image {
    width: 110rpx;
    height: 26rpx;
    border-radius: 0;
  }

  .productSort .conter .list {
    flex-wrap: wrap;
    background: #fff;
    border-radius: 16rpx;
    padding-bottom: 26rpx;
  }

  .productSort .conter .list .item {
    width: 174rpx;
    margin-top: 26rpx;
  }

  .productSort .conter .list .item .picture,
  .productSort .conter uni-image,
  .productSort .conter .list .item image,
  ::v-deep .easy-loadimage {
    width: 110rpx;
    height: 110rpx;
    border-radius: 50%;
  }

  .productSort .conter .list .item .name {
    font-size: 24rpx;
    color: #333;
    height: 56rpx;
    line-height: 56rpx;
    width: 120rpx;
    text-align: center;
  }

  .block {
    display: inline-block;
  }

  // 加载状态样式
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    
    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid $active-color;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 20rpx;
    }
    
    .loading-text {
      font-size: 28rpx;
      color: $text-gray;
    }
  }

  // 错误状态样式
  .error-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    
    .error-icon {
      font-size: 80rpx;
      margin-bottom: 20rpx;
    }
    
    .error-text {
      font-size: 28rpx;
      color: #ff4d4f;
      margin-bottom: 10rpx;
    }
    
    .retry-text {
      font-size: 24rpx;
      color: $active-color;
      text-decoration: underline;
    }
  }

  // 空状态样式
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    
    .empty-icon {
      font-size: 80rpx;
      margin-bottom: 20rpx;
    }
    
    .empty-text {
      font-size: 28rpx;
      color: $text-gray;
    }
  }

  // 加载更多样式
  .load-more-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40rpx 0;
    
    .loading-more {
      display: flex;
      align-items: center;
      
      .loading-spinner-small {
        width: 30rpx;
        height: 30rpx;
        border: 2rpx solid #f3f3f3;
        border-top: 2rpx solid $active-color;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-right: 10rpx;
      }
      
      .loading-more-text {
        font-size: 24rpx;
        color: $text-gray;
      }
    }
    
    .load-end {
      .load-end-text {
        font-size: 24rpx;
        color: $text-gray;
      }
    }
    
    .load-more-btn {
      padding: 20rpx 40rpx;
      background-color: $active-color;
      border-radius: 50rpx;
      
      .load-more-text {
        font-size: 24rpx;
        color: white;
      }
    }
  }

  // 旋转动画
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
}
</style>